package com.athena.framework.config;

import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;

/**
 * 读取ContentType.txt文件并个保存
 */
public class HttpContentType {

    private final static Logger logger = LoggerFactory.getLogger(HttpContentType.class);


    /**
     * 保存ContentType内容，方便查找
     */
    private static HashMap<String, String> contentType = new HashMap<>();

    /**
     * 读取文件并保存
     * @throws IOException
     */
    public static void init() throws IOException {
        if (logger.isInfoEnabled()){
            logger.info("初始化HttpContentType...");
        }
        ClassPathResource classPathResource = new ClassPathResource("ContentType.txt");
        BufferedReader reader = classPathResource.getReader(CharsetUtil.CHARSET_UTF_8);
        String line = null;
        while ((line = reader.readLine()) != null) {
            if (StrUtil.isNotBlank(line)) {
                line = StrUtil.trim(line);
                String[] split = StrUtil.split(line, "=");
                if (split.length != 2) {
                    continue;
                }
                contentType.put(split[0],split[1]);
            }
        }
    }

    /**
     * 根据文件后最获取content type
     * @param key 文件后最，如：.html
     * @return
     */
    public static String get(String key){
        return contentType.get(key);
    }
}
